package coin

import (
	"bytes"
	"crypto/sha256"
	"strconv"
	"time"
)

type Block struct {
	TimeStamp     int64//时间戳
	Data          []byte//存储的数据信息
	PrevBlockHash []byte// 上一个区块的hash
	Hash          []byte//本区块的hash
}

// 创建一个新的区块
func NewBlock(data string, prevBlockHash []byte) *Block {
	// 新建一个区块，自己hash值为空
	block := &Block{time.Now().Unix(), []byte(data), prevBlockHash, []byte{}}
	// 计算自己区块的hash值
	block.SetHash()
	return block
}


func (b *Block) SetHash() {
	strTimeStamp := []byte(strconv.FormatInt(b.TimeStamp, 10))
	headers := bytes.Join([][]byte{b.PrevBlockHash, b.Data, strTimeStamp}, []byte{})
	hash := sha256.Sum256(headers)
	b.Hash = hash[:]
}

// 模拟创世区块
func NewGenesisBlock() *Block {
	return NewBlock("创世区块", []byte{})
}